<template>
  <u-popup :show="show" @close="close" mode="center" round="24rpx" closeable>
    <view class="pop-content p-12">
      <view class="avatar-box">
        <u-avatar size="100rpx"></u-avatar>
      </view>
      <view class="text-center text-14 pt-48">
        欢迎来到{{ platformName }}
      </view>
      <view class="text-center text-14">使用手机号登录,提供订单售后服务</view>
      <view class="flex pt-48">
        <u-checkbox-group v-model="checked">
          <u-checkbox
            activeColor="#86bf9e"
            labelSize="12px"
            label-color="#666666"
            :size="12"
            name="check"
            label="阅读并同意"
            shape="circle"
          ></u-checkbox>
        </u-checkbox-group>

        <span class="text-12 color-primary">《 隐私协议 》</span>
      </view>
      <view class="mt-12">
        <u-button
          type="primary"
          size="large"
          @getphonenumber="handelLogin"
          open-type="getPhoneNumber"
          :loading="loading"
          shape="circle"
          v-if="checked.length === 1"
          >授权手机号码</u-button
        >
        <u-button
          type="primary"
          size="large"
          @click="handelLogin"
          :loading="loading"
          shape="circle"
          v-else
          >授权手机号码</u-button
        >
      </view>

      <view class="text-center text-14 mt-12 color-gray" @click="close"
        >暂不登录</view
      >
    </view>
  </u-popup>
</template>

<script>
import {
  fetchCustomerIdentityList,
  fetchCustomerOpenId,
  fetchLogin,
  fetchToken,
} from "@/services/api";
import { mapMutations } from "vuex";
import { platformName, tenantId } from "@/envConfig";
export default {
  data() {
    return {
      checked: false,
      openid: "",
      sessionKey: "",
      token: "",
      loading: false,
      show: false,
    };
  },
  methods: {
    ...mapMutations("user", {
      setToken: "setToken",
      setIdentityList: "setIdentityList",
      setCurrentIdentity: "setCurrentIdentity",
    }),
    close() {
      this.show = false;
    },
    open() {
      this.show = true;
    },
    async handelLogin(e) {
      console.log("获取的结果是", e);
      if (!this.checked) {
        uni.$u.toast("请勾选隐私协议");
      }
      this.loading = true;
      try {
        const accountInfo = uni.getAccountInfoSync();
        console.log("账户信息是", accountInfo.miniProgram);
        if (e.detail.errMsg === "getPhoneNumber:fail no permission") {
          uni.$u.toast("暂无权限,请使用其他登录方式");
          return;
        }
        let param = {
          appId: accountInfo.miniProgram.appId,
          openId: this.openid,
          sessionKey: this.sessionKey,
          encryptedData: e.detail.encryptedData,
          iv: e.detail.iv,
        };
        const { data, error } = await fetchLogin({
          ...param,
          // 0、手机号 1、邮箱 2、QQ 3、微信 4、用户名 5、微博  第三方登录获取
          authMethod: 3,
          // 微信授权登录，使用openId作为username,无需再传
          tenantId,
        });
        if (!error) {
          this.setToken(data.token);

          // 登录
          this.$emit("afterLogin", data);
          //设置用户身份列表
          this.setIdentityList(data.identityList);
          this.setCurrentIdentity(data.identityList[0]);
          this.close();
        } else {
          this.setToken(null);
        }
      } catch (e) {
        console.log(e);
      } finally {
        this.loading = false;
      }
    },

    initLogin() {
      return new Promise((resolve, reject) => {
        uni.login({
          provider: "weixin",
          onlyAuthorize: true,
          success: async ({ code }) => {
            const accountInfo = uni.getAccountInfoSync();
            const appId = accountInfo.miniProgram.appId;
            //通过小程序appId  code 发起请求获取openid 和 sessionKey
            const { data, error } = await fetchCustomerOpenId({
              appId,
              code,
              tenantId,
            });
            if (!error) {
              const { openId, sessionKey } = data;
              // this.token = token;

              this.openid = openId;
              this.sessionKey = sessionKey;
              resolve();
            } else {
              reject(error);
            }
          },
        });
      });
    },
  },
  async mounted() {
    try {
      this.loading = true;
      await this.initLogin();
    } catch (e) {
    } finally {
      this.loading = false;
    }
  },
};
</script>

<style lang="scss" scoped>
.pop-content {
  width: 654rpx;
  position: relative;

  .avatar-box {
    position: absolute;
    top: -50rpx;
    left: 50%;
    transform: translateX(-50%);
  }
}
</style>
